package com.dongbing.support.strategy.impl;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dongbing.entity.base.BaseEntity;
import com.dongbing.entity.support.BatchTaskDetailPO;
import com.dongbing.entity.support.BatchTaskPO;
import com.dongbing.enums.BatchTaskDetailState;
import com.dongbing.support.CollectBeanPostProcessor;
import com.dongbing.support.context.BatchTaskContext;
import com.dongbing.support.executor.BatchTaskExecutor;
import com.dongbing.support.result.TaskExecuteResult;
import com.dongbing.support.strategy.BatchTaskExecutorStrategy;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class LocalBatchTaskExecutorStrategy extends BatchTaskExecutorStrategy {

    @SuppressWarnings("all")
    @Override
    public List<BatchTaskDetailPO> execute(BatchTaskPO task, JSONObject msgBody) {
        BatchTaskExecutor batchTaskExecutor = CollectBeanPostProcessor.getExecutor(task.getBizType());
        // 获取实体类Class
        Class clazz = batchTaskExecutor.entityClass();
        List<Long> ids = Arrays.stream(msgBody.getJSONArray("datas").toArray()).map(item -> Long.parseLong(String.valueOf(item))).collect(Collectors.toList());
        List datas = ids.stream()
                .map(id -> {
                    Object obj = ReflectUtil.newInstance(clazz);
                    ReflectUtil.setFieldValue(obj, "id", id);
                    return obj;
                }).collect(Collectors.toList());

        List<TaskExecuteResult<Object>> results;
        BatchTaskContext.set(task);
        try {
            results = batchTaskExecutor.batchExecute(task.getBizType(), datas);
        } finally {
            BatchTaskContext.clear();
        }
        if (CollectionUtils.isNotEmpty(results)) {
            //创建任务明细，并更新任务
            List<BatchTaskDetailPO> details = new ArrayList<>();
            for (TaskExecuteResult<Object> result : results) {
                BatchTaskDetailPO batchTaskDetailPO = result.getBatchTaskDetailPO();
                if (Objects.isNull(batchTaskDetailPO)) {
                    batchTaskDetailPO = new BatchTaskDetailPO();
                }
                batchTaskDetailPO.setBatchTaskId(task.getId());
                batchTaskDetailPO.setDataId(((BaseEntity) result.getData()).getId());
                batchTaskDetailPO.setState(result.getSuccess() ? BatchTaskDetailState.SUCCESS : BatchTaskDetailState.FAILED);
                batchTaskDetailPO.setErrMsg(StringUtils.isNotBlank(result.getErrMsg()) ? result.getErrMsg().length() > 400 ? result.getErrMsg().substring(0, 400) : result.getErrMsg() : null);
                details.add(batchTaskDetailPO);
            }
            return details;
        }
        return null;
    }
}
